/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);

var type = "";
//表格初始化配置
var tableInit = function () {
    var columns = [
        {
            title: '全选',
            field: 'select',
            //复选框
            checkbox: true,
            width: 25,
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'id',
            title: 'ID',
            align: 'center',
            valign: 'middle',
        },
        {
            field: 'name',
            title: '名称',
            align: 'center',
            valign: 'middle',
        },
        {
            field: 'type',
            title: '优惠券类型',
            align: 'center',
            valign: 'middle',
            formatter: function (value) {
                if (!empty(value)) {
                    value = typeMap.get(value);
                    if (empty(value)) {
                        return "暂无";
                    }
                    return '<span class="label label-success">' + value + '</span>';
                } else {
                    return "暂无";
                }
            }
        },
        {
            field: 'couponMoney',
            title: '优惠券面值',
            align: 'center',
            valign: 'middle',
            formatter: function (value, row, index) {
                if (!empty(row.type)) {
                    var val = typeMap.get(row.type);
                    if (empty(val)) {
                        return value;
                    }
                    if (val.indexOf("折扣") != -1) {
                        return value + " 折";
                    } else {
                        return value + " 元";
                    }
                } else {
                    return value;
                }
            }
        },
        {
            field: 'minUseMoney',
            title: '最低消费金额',
            align: 'center',
            valign: 'middle',
        },
        {
            field: 'useTerm',
            title: '使用期限天数',
            align: 'center',
            valign: 'middle',
        },
        {
            field: 'status',
            title: '是否有效',
            align: 'center',
            valign: 'middle',
            formatter: function (value, row, index) {
                if (value == 1) {
                    return '<span class="label label-primary">有效</span>';
                }
                return '<span class="label label-danger">失效</span>';
            }
        },
        {
            field: 'sort',
            title: '排序',
            align: 'center',
            valign: 'middle',
            width: '5%',
        },
        {
            field: 'schoolId',
            title: '学校',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == null) {
                    return '<span class="label label-warning">公用</span>';
                }
                if (value == schoolId) {
                    return '<span class="label label-primary">' + schoolMap[value] + '</span>';
                } else {
                    return '<span class="label label-warning">' + schoolMap[value] + '</span>';
                }
            }
        },
        {
            field: 'gmtCreate',
            title: '创建时间',
            align: 'center',
            visible: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        },
        {
            field: 'gmtModified',
            title: '更新时间',
            align: 'center',
            visible: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        }
    ];

    //请求服务数据时所传参数
    function queryParams(params) {
        return {
            pageNumber: params.pageNumber,
            pageSize: params.pageSize,
            companyId: companyId,
            schoolId: schoolId,
            status: $("#status").val(),
            type: type,
            searchText: params.searchText,
        }
    }

    var tableConfig = $.extend(bootstrapTableConfig(_HOST + _API.marketing_coupon_list, queryParams, columns), {
        //这里是其他的一些个性化的 bootstrap-table options
        showColumns: true,//列显示操作按钮
        ajaxOptions: { //设置自定义请求头
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': 'coupon:list'
            }
        },
        //例如格式化数据
        responseHandler: function (res) {
            //在ajax获取到数据，渲染表格之前，修改数据源
            //console.log(res)
            if (res.success) {
                //更新本地token
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.token, res.token);
            }
            return res;
        }
    });
    //调用实例化
    $('#bootstrapTableEvents').bootstrapTable(tableConfig);
    $(".search input").attr('placeholder', '输入名称搜索');
};

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['coupon:add', 'coupon:batchStatus', 'coupon:del', 'coupon:list', 'couponPush:batchPushCoupon'],//本页权限数组
        selects: [],
        typeIndex: 0,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);

            return;
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        // 得到字典map
        getDicList: function (keyTable) {
            var that = this;
            var ret = new Map();
            that.selects = [{keyS: "", keyValue: "全部"}];
            Get(that, _HOST + _API.common_dic_dicList + "?keyTable=" + keyTable)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            that.selects = that.selects.concat(response.list);
                            var list = response.list;
                            for (var i = 0; i < list.length; i++) {
                                ret.set(parseInt(list[i].keyS), list[i].keyValue);
                            }
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                });
            return ret;
        },
        selectStatus: function () {
            $('#bootstrapTableEvents').bootstrapTable('refresh');
        },
        selectType: function (index) {
            var that = this;
            that.typeIndex = index;
            type = that.selects[index].keyS;
            $('#bootstrapTableEvents').bootstrapTable('refresh');
        },
        //添加
        add: function () {
            var that = this;
            var index = layer.open({
                type: 2,
                title: "新增",
                content: "edit.html?id=",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        // 发布
        push: function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var ids = "";
            var flag2 = true;
            for (let i = 0; i < list.length; i++) {
                ids += list[i].id;
                if ((i + 1) != list.length) {
                    ids += ",";
                }
                if (!empty(schoolId)) {
                    if (schoolId != list[i].schoolId) {
                        flag2 = false;
                        break;
                    }
                }
            }
            // 判断是否有权操作
            if (!flag2) {
                layer.msg('非本校区数据，不可操作!', {time: 1500, icon: 5});
                return;
            }
            var index = layer.open({
                type: 2,
                title: "发布配置",
                content: "push.html?ids="+ids,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '80%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        //修改
        update: function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var flag2 = true;
            for (let i = 0; i < list.length; i++) {
                list[i].status = 0;
                list[i].version = list[i].version + 1;
                if (!empty(schoolId)) {
                    if (schoolId != list[i].schoolId) {
                        flag2 = false;
                        break;
                    }
                }
            }
            // 判断是否有权操作
            if (!flag2) {
                layer.msg('非本校区数据，不可操作!', {time: 1500, icon: 5});
                return;
            }

            var confirm = layer.confirm('确定立即失效选中项？', {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Put(that, _HOST + _API.marketing_coupon_batchStatus, list, true, that.permissions[index])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        layer.close(confirm);
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, {time: 1500, icon: 1});
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                    })
            });
        },
        //删除
        del: function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var ids = "";
            var flag2 = true;
            for (let i = 0; i < list.length; i++) {
                ids += list[i].id;
                if ((i + 1) != list.length) {
                    ids += ",";
                }
                if (!empty(schoolId)) {
                    if (schoolId != list[i].schoolId) {
                        flag2 = false;
                        break;
                    }
                }
            }
            // 判断是否有权操作
            if (!flag2) {
                layer.msg('非本校区数据，不可操作!', {time: 1500, icon: 5});
                return;
            }

            var confirm = layer.confirm('确定删除选中项？', {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Put(that, _HOST + _API.marketing_coupon_delete + "/" + ids, {}, true, that.permissions[index])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        layer.close(confirm);
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, {time: 1500, icon: 1});
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                    })
            });

        },
    },
});

var typeMap = app.getDicList("couponType");

$(function () {
    //初始化表格
    tableInit();
});
